package com.credithc.customers.dataservice.service.impl;

import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.base.constants.ProductTypeConstants;
import com.credithc.customers.dataservice.Thread.OldDataThreadPoolExecutor;
import com.credithc.customers.dataservice.constants.SyncTypeEnum;
import com.credithc.customers.dataservice.constants.TableNameConstants;
import com.credithc.customers.dataservice.mapper.HYR.HyrMapper;
import com.credithc.customers.dataservice.po.*;
import com.credithc.customers.dataservice.ro.CustomerAccountInfoRo;
import com.credithc.customers.dataservice.ro.CustomerProductInfoRo;
import com.credithc.customers.dataservice.ro.ProductInfoRo;
import com.credithc.customers.dataservice.service.OldHyrDataService;
import com.credithc.customers.dataservice.service.SyncDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;

import static com.credithc.customers.dataservice.service.impl.CustomerProductInfoServiceImpl.getYZTStatus;

@Service
@Slf4j
public class OldHyrDataServiceImpl implements OldHyrDataService {
    @Autowired
    HyrMapper hyrMapper;
    @Autowired
    SyncDataService syncDataService;
    @Autowired
    private OldDataThreadPoolExecutor oldDataThreadPoolExecutor;
    //long vernier = Long.MAX_VALUE;
    @Override
    public void oldProduct() {
        boolean f =true;
        Long num = null;
        try {
            num = hyrMapper.queryProductMaxId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num == null ){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+10001);
        ExecutorService e = oldDataThreadPoolExecutor.getCustomThreadPoolExecutor();
        while (f) {
            e.submit(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-10000);
                    }
                    List<SystemProductPo> systemProductPos = hyrMapper.queryHyrProduct(Long.toString(vernier.get()));
                    log.info("开始导入 从"+vernier.get() +"后10000条" );
                    if (systemProductPos.size() > 0) {
                        bulidHyrProduct(systemProductPos);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = exit(f, vernier, e);
        }

    }

    private void bulidHyrProduct(List<SystemProductPo> systemProductPos) {
        List<ProductInfoRo> productInfoRos = new ArrayList<>();
        for (SystemProductPo d: systemProductPos) {
            ProductInfoRo productInfoRo = new ProductInfoRo();
            productInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
            productInfoRo.setDatabaseName(TableNameConstants.HYR_DATABASE);
            productInfoRo.setTableName(TableNameConstants.HYR_PRODUCT_DTPAY);
            productInfoRo.setProductChannel("HYR");
            productInfoRo.setSubSystemSign("HYR");
            productInfoRo.setSystemSign("HYR");
            productInfoRo.setProductCreateTime(d.getCreatTime());
            productInfoRo.setProductType(Integer.toString(ProductTypeConstants.P2P_LEND));
            productInfoRo.setProductNo(d.getId());
            productInfoRo.setTableKey(d.getIncrementId()+"");
            productInfoRo.setProductName(d.getProductName());
            productInfoRos.add(productInfoRo);
        }
        syncDataService.syncProduct(productInfoRos);
    }

    @Override
    public void oldUser(Integer start) {
        boolean f =true;
        Long num = null ;
        if (start == null) {
            num = hyrMapper.queryUserMaxId();
        }else {
            num =Long.valueOf(start);
        }
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+10001);
        ExecutorService e = oldDataThreadPoolExecutor.getCustomThreadPoolExecutor();
        log.info("开始导入 从"+vernier.get() +"后10000条" );
        while (f) {
            e.execute(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-10000);
                    }
                    List<SystemUserPo> systemUserPos = hyrMapper.queryHyrUser(Long.toString(vernier.get()));
                    if (systemUserPos.size() > 0) {
                        bulidHyrUser(systemUserPos);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = exit(f, vernier, e);
        }
    }

    public static boolean exit(boolean f, AtomicReference<Long> vernier, ExecutorService e) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        if (vernier.get() < 0) {
            f = false;
            try {
                Thread.sleep(5000000);
            } catch (InterruptedException e1) { }
            e.shutdown();

        }
        return f;
    }

    private void bulidHyrUser(List<SystemUserPo> dlrQmUserRos) {
        List<CustomerAccountInfoRo> customerAccountInfoRos = new ArrayList<>();
        for (SystemUserPo u:dlrQmUserRos) {
            CustomerAccountInfoRo customerAccountInfoRo = new CustomerAccountInfoRo();
            customerAccountInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
            customerAccountInfoRo.setSubSystemSign("HYR");
            customerAccountInfoRo.setSystemSign("HYR");
            customerAccountInfoRo.setAccountCreateTime(u.getCreatTime());

            customerAccountInfoRo.setAccountNo(u.getCustomerId());
            customerAccountInfoRo.setCustomerNo(u.getCustomerNo());
            customerAccountInfoRo.setAccountType(u.getUserType() ==Integer.parseInt(CustomerConstants.DLR_ACCOUNT_TYPE_LEND) ? CustomerConstants.CUSTOMER_ACCOUNT_TYPE_LEND:CustomerConstants.CUSTOMER_ACCOUNT_TYPE_LOAN);
            customerAccountInfoRo.setUserSourceId(u.getUserId());
            customerAccountInfoRo.setAccountStatus(StringUtils.isNotBlank(customerAccountInfoRo.getAccountNo())?CustomerConstants.STATUS_ACCOUNT_AVAILABLE:CustomerConstants.STATUS_ACCOUNT_UNAVAILABLE);
            customerAccountInfoRo.setCustomerRole(u.getUserType() ==Integer.parseInt(CustomerConstants.HYR_ACCOUNT_TYPE_LEND) ? 1+"":2+"");
            if (StringUtils.isNotBlank(customerAccountInfoRo.getAccountNo()) && StringUtils.isNotBlank(customerAccountInfoRo.getCustomerNo())){
                customerAccountInfoRos.add(customerAccountInfoRo);
            }

        }
        syncDataService.syncCustomerAccount(customerAccountInfoRos);
    }

    @Override
    public void oldBankCard() {
        boolean f =true;
        Long num = hyrMapper.queryBanckMaxId();
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+10001);
        ExecutorService e = oldDataThreadPoolExecutor.getCustomThreadPoolExecutor();
        while (f) {
            e.submit(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-10000);
                    }
                    List<SystemUserPo> systemUserPos = hyrMapper.queryHyrBankCard(Long.toString(vernier.get()));
                    log.info("开始导入 从"+vernier.get() +"后10000条" );
                    if (systemUserPos.size() > 0) {
                        bulidHyrBank(systemUserPos);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = exit(f, vernier, e);
        }
    }


    private void bulidHyrBank(List<SystemUserPo> dlrQmUserRos) {
        List<CustomerAccountInfoRo> customerAccountInfoRos = new ArrayList<>();
        for (SystemUserPo u:dlrQmUserRos) {
            CustomerAccountInfoRo customerAccountInfoRo = new CustomerAccountInfoRo();
            customerAccountInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
            customerAccountInfoRo.setSubSystemSign("HYR");
            customerAccountInfoRo.setSystemSign("HYR");
            customerAccountInfoRo.setAccountCreateTime(u.getCreatTime());
            customerAccountInfoRo.setUserSourceId(u.getUserId());
            customerAccountInfoRo.setAccountType(CustomerConstants.CUSTOMER_ACCOUNT_TYPE_BANK_CARD);
            customerAccountInfoRo.setAccountNo(u.getCustomerId());
            customerAccountInfoRo.setCustomerNo(u.getCustomerNo());
            customerAccountInfoRo.setAccountStatus(StringUtils.isNotBlank(customerAccountInfoRo.getAccountNo())?CustomerConstants.STATUS_ACCOUNT_AVAILABLE:CustomerConstants.STATUS_ACCOUNT_UNAVAILABLE);
            if (StringUtils.isNotBlank(customerAccountInfoRo.getAccountNo()) && StringUtils.isNotBlank(customerAccountInfoRo.getCustomerNo())){
                customerAccountInfoRos.add(customerAccountInfoRo);
            }

        }
        syncDataService.syncCustomerAccount(customerAccountInfoRos);
    }
    @Override
    public void oldLend() {
        boolean f =true;
        Long num = hyrMapper.querylendMaxId();
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+10001);
        ExecutorService e = oldDataThreadPoolExecutor.getCustomThreadPoolExecutor();
        while (f) {
            e.submit(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-10000);
                    }
                    List<HyrOrderPo> systemUserPos = hyrMapper.querylend(Long.toString(vernier.get()));
                    log.info("开始导入 从"+vernier.get() +"后10000条" );
                    if (systemUserPos.size() > 0) {
                        bulidHyrlend(systemUserPos);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = exit(f, vernier, e);
        }
    }

    private void bulidHyrlend(List<HyrOrderPo> systemUserPos) {
        List<CustomerProductInfoRo> customerProductInfoRos = new ArrayList<>();

        for (HyrOrderPo d:systemUserPos) {
            SystemLendPo hyrOrderPo = null;
            if ("1".equals(d.getDtbType()) && StringUtils.isNotBlank(d.getCrmid())) {
                hyrOrderPo = hyrMapper.selectfixCP(d.getCrmid());
            } else if ("2".equals(d.getDtbType()) && StringUtils.isNotBlank(d.getCrmid())) {
                hyrOrderPo = hyrMapper.selectThrowCP(d.getCrmid());
            } else if ("4".equals(d.getDtbType()) && StringUtils.isNotBlank(d.getCrmid())) {
                hyrOrderPo = hyrMapper.selectOrderCP(d.getCrmid());
            }
            if (hyrOrderPo != null) {
                CustomerProductInfoRo customerProductInfoRo = new CustomerProductInfoRo();
                customerProductInfoRo.setSubSystemSign(CustomerConstants.HYR);
                customerProductInfoRo.setSystemSign(CustomerConstants.HYR);
                customerProductInfoRo.setProductSourceSystem(CustomerConstants.HYR_CODE + "");
                customerProductInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
                customerProductInfoRo.setTableKey(d.getId());
                customerProductInfoRo.setProductAmount(hyrOrderPo.getAmount());
                customerProductInfoRo.setProductNo(hyrOrderPo.getProductId());
                customerProductInfoRo.setProductStartTime(hyrOrderPo.getCapitalEffectDate());
                customerProductInfoRo.setProductEndTime(hyrOrderPo.getExpireDate());
                customerProductInfoRo.setProductDeadline(hyrOrderPo.getPeriod() * 30 + "");
                customerProductInfoRo.setUserResourceId(hyrOrderPo.getUserId());
                CustomerNoPo byUserId = hyrMapper.getByUserId(hyrOrderPo.getUserId());
                if (byUserId != null) {
                    customerProductInfoRo.setCustomerNo(byUserId.getCustomerNo());
                    customerProductInfoRo.setPreCustomerNo(byUserId.getPreCustomerNo());

                }
                customerProductInfoRo.setProductStatus(getYZTStatus(CustomerConstants.HYR + d.getStatus()));
                if (StringUtils.isNotBlank(customerProductInfoRo.getCustomerNo())) {
                    customerProductInfoRos.add(customerProductInfoRo);
                }
            }
        }
        syncDataService.syncCustomerProduct(customerProductInfoRos);
    }


    /*@Override
    public void oldFixLend() {
        boolean f =true;
        Long num = hyrMapper.queryFixMaxId();
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+1001);
        ExecutorService e = new OldDataThreadPoolExecutor().getCustomThreadPoolExecutor();
        while (f) {
            e.submit(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-1000);
                    }
                    List<SystemLendPo> systemLendPos = hyrMapper.queryHyrFixLend(Long.toString(vernier.get()));
                    if (systemLendPos.size() > 0) {
                        bulidHyrFixLend(systemLendPos);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = exit(f, vernier, e);
        }
    }*/

   /* private void bulidHyrFixLend(List<SystemLendPo> dlrLendRos) {
        List<CustomerProductInfoRo> customerProductInfoRos = new ArrayList<>();
        for (SystemLendPo d:dlrLendRos){
            CustomerProductInfoRo customerProductInfoRo = new CustomerProductInfoRo();
            customerProductInfoRo.setDatabaseName(TableNameConstants.HYR_DATABASE);
            customerProductInfoRo.setTableName(TableNameConstants.HYR_CUSTOMER_PRODUCT_ORDERFIXINVEST);
            customerProductInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
            customerProductInfoRo.setSubSystemSign("HYR");
            customerProductInfoRo.setSystemSign("HYR");
            customerProductInfoRo.setProductSourceSystem(CustomerConstants.HYR_CODE+"");
            //customerProductInfoRo.setCustomerRoleStatus(1);
            customerProductInfoRo.setProductAmount(d.getAmount());
            customerProductInfoRo.setProductNo(d.getProductId());
            customerProductInfoRo.setProductStartTime(d.getCapitalEffectDate());
            customerProductInfoRo.setProductEndTime(d.getExpireDate());
            customerProductInfoRo.setProductDeadline(d.getPeriod()+"");
            customerProductInfoRo.setProductStatus(CustomerProductInfoServiceImpl.getYZTStatus("HYR_FIX"+d.getSts()));
            customerProductInfoRo.setUserResourceId(d.getUserId());
            CustomerNoPo byUserId = hyrMapper.getByUserId(d.getUserId());
            if (byUserId !=null){
                customerProductInfoRo.setCustomerNo(byUserId.getCustomerNo());
                customerProductInfoRo.setPreCustomerNo(byUserId.getPreCustomerNo());
            }

            customerProductInfoRos.add(customerProductInfoRo);
        }
        syncDataService.syncCustomerProduct(customerProductInfoRos);
    }

    @Override
    public void oldThrowLend() {
        boolean f =true;
        Long num = hyrMapper.queryThrowMaxId();
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+1001);
        ExecutorService e = new OldDataThreadPoolExecutor().getCustomThreadPoolExecutor();
        while (f) {
            e.submit(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-1000);
                    }
                    List<SystemLendPo> systemLendPos = hyrMapper.queryHyrThrowLend(Long.toString(vernier.get()));
                    if (systemLendPos.size() > 0) {
                        bulidHyrThrowLend(systemLendPos);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = exit(f, vernier, e);
        }

    }

    private void bulidHyrThrowLend(List<SystemLendPo> dlrLendRos) {
        List<CustomerProductInfoRo> customerProductInfoRos = new ArrayList<>();
        for (SystemLendPo d:dlrLendRos){
            CustomerProductInfoRo customerProductInfoRo = new CustomerProductInfoRo();
            customerProductInfoRo.setDatabaseName(TableNameConstants.HYR_DATABASE);
            customerProductInfoRo.setTableName(TableNameConstants.HYR_CUSTOMER_PRODUCT_HYR_THROW_NEW);
            customerProductInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
            customerProductInfoRo.setSubSystemSign("HYR");
            customerProductInfoRo.setSystemSign("HYR");
            customerProductInfoRo.setProductSourceSystem(CustomerConstants.HYR_CODE+"");
            customerProductInfoRo.setProductAmount(d.getAmount());
            customerProductInfoRo.setProductNo(d.getProductId());
            customerProductInfoRo.setProductStartTime(d.getCapitalEffectDate());
            customerProductInfoRo.setProductEndTime(d.getExpireDate());
            customerProductInfoRo.setProductDeadline(d.getPeriod()+"");
            //customerProductInfoRo.setProductStatus(CustomerProductInfoServiceImpl.getYZTStatus("HYR_THROW"+d.getSts()));
            customerProductInfoRo.setUserResourceId(d.getUserId());
            CustomerNoPo byUserId = hyrMapper.getByUserId(d.getUserId());
            if (byUserId !=null){
                customerProductInfoRo.setCustomerNo(byUserId.getCustomerNo());
                customerProductInfoRo.setPreCustomerNo(byUserId.getPreCustomerNo());
                *//*if (byUserId.getCustomerNo()!=null){
                    customerProductInfoRo.setCustomerRole(getCustomerRole(byUserId.getCustomerNo(),"HYR","HYR"));
                }else{
                    customerProductInfoRo.setCustomerRole(getCustomerRole(byUserId.getPreCustomerNo(),"HYR","HYR"));
                }*//*
            }

            customerProductInfoRos.add(customerProductInfoRo);
        }
        syncDataService.syncCustomerProduct(customerProductInfoRos);
    }

    @Override
    public void oldCrightLend() {
        boolean f =true;
        Long num = hyrMapper.queryCrightMaxId();
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+1001);
        ExecutorService e = new OldDataThreadPoolExecutor().getCustomThreadPoolExecutor();
        while (f) {
            e.submit(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-1000);
                    }
                    List<SystemLendPo> systemLendPos = hyrMapper.queryHyrCrightLend(Long.toString(vernier.get()));
                    if (systemLendPos.size() > 0) {
                        bulidHyrCrightLend(systemLendPos);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = exit(f, vernier, e);
        }

    }

    private void bulidHyrCrightLend(List<SystemLendPo> dlrLendRos) {
        List<CustomerProductInfoRo> customerProductInfoRos = new ArrayList<>();
        for (SystemLendPo d:dlrLendRos){
            CustomerProductInfoRo customerProductInfoRo = new CustomerProductInfoRo();
            customerProductInfoRo.setDatabaseName(TableNameConstants.HYR_DATABASE);
            customerProductInfoRo.setTableName(TableNameConstants.HYR_CUSTOMER_PRODUCT_ORDERCRIGHT);
            customerProductInfoRo.setSyncType(SyncTypeEnum.NEW.getValue());
            customerProductInfoRo.setSubSystemSign("HYR");
            customerProductInfoRo.setSystemSign("HYR");
            customerProductInfoRo.setProductSourceSystem(CustomerConstants.HYR_CODE+"");
            customerProductInfoRo.setProductAmount(d.getAmount());
            customerProductInfoRo.setProductNo(d.getProductId());
            customerProductInfoRo.setProductStartTime(d.getCapitalEffectDate());
            customerProductInfoRo.setProductEndTime(d.getExpireDate());
            customerProductInfoRo.setProductDeadline(d.getPeriod()+"");
            customerProductInfoRo.setProductStatus(CustomerProductInfoServiceImpl.getYZTStatus("HYR_CRIGHT"+d.getSts()));
            customerProductInfoRo.setUserResourceId(d.getUserId());
            CustomerNoPo byUserId = hyrMapper.getByUserId(d.getUserId());
            if (byUserId !=null){
                customerProductInfoRo.setCustomerNo(byUserId.getCustomerNo());
                customerProductInfoRo.setPreCustomerNo(byUserId.getPreCustomerNo());

            }

            customerProductInfoRos.add(customerProductInfoRo);
        }
        syncDataService.syncCustomerProduct(customerProductInfoRos);
    }

*/

}
